package com.panfeng.xcloud.boss.provider.assets.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.panfeng.xcloud.common.core.enums.ResponseStatusEnum;
import com.panfeng.xcloud.common.core.web.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份认证异常endpoint
 *
 * @author xiaobo
 * @version 1.0
 * @since 2018-12-28
 */
@Configuration
@Slf4j
public class AssetsAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        Throwable cause = authException.getCause();
        ResponseVO responseTmp = new ResponseVO();

        String message = authException.getMessage();
        responseTmp.setData(message);

        if (cause instanceof InvalidTokenException) {
            responseTmp.setCode(ResponseStatusEnum.INVALID_TOKEN.getCode());
            responseTmp.setMessage(ResponseStatusEnum.INVALID_TOKEN.getMessage());
        } else {
            responseTmp.setCode(ResponseStatusEnum.NOT_LOGIN_ERROR.getCode());
            responseTmp.setMessage(ResponseStatusEnum.NOT_LOGIN_ERROR.getMessage());
        }
        log.error(">>> AssetsAuthExceptionEntryPoint,响应码：{}，响应信息：{}异常信息：{} <<<",responseTmp.getCode(),responseTmp.getMessage(),cause);
        String json = objectMapper.writeValueAsString(responseTmp);

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
    }
}
